package com.sunseagear.wind.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunseagear.common.base.mvc.service.impl.CommonServiceImpl;
import com.sunseagear.common.utils.StringUtils;
import com.sunseagear.wind.modules.sys.entity.User;
import com.sunseagear.wind.modules.sys.mapper.UserMapper;
import com.sunseagear.wind.modules.sys.service.IRoleService;
import com.sunseagear.wind.modules.sys.service.IUserRoleService;
import com.sunseagear.wind.modules.sys.service.IUserService;
import com.sunseagear.wind.common.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service("userService")
@RequiredArgsConstructor
public class UserServiceImpl extends CommonServiceImpl<UserMapper, User> implements IUserService {
    private final PasswordService passwordService;
    private final IUserRoleService userRoleService;
    private final IRoleService roleService;

    @Override
    public void changePassword(Long userId, String newPassword) {
        User user = getById(userId);
        if (user != null) {
            user.setPassword(passwordService.getPassword(newPassword));
            updateById(user);
        } else {
            throw new RuntimeException("用戶不存在");
        }
    }


    @Override
    public User findByUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            return null;
        }
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return null;
        }
        user.setRoles(roleService.findListByUserId(user.getId()));
        return user;
    }

    @Override
    public User findByEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return null;
        }
        User user = getOne(new QueryWrapper<User>().eq("email", email));
        if (user == null) {
            return null;
        }
        user.setRoles(roleService.findListByUserId(user.getId()));
        return user;

    }

    @Override
    public User findByPhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return null;
        }
        User user = getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            return null;
        }
        user.setRoles(roleService.findListByUserId(user.getId()));
        return user;
    }

    /**
     * 根据id获取用户详情
     *
     * @param userId
     */
    @Override
    public User getById(Long userId) {
        return baseMapper.findById(userId);
    }


    /**
     * 加载用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public User loadUserByUsername(String username) {
        User user = this.findByUsername(username);
        if (user == null) {
            user = this.findByEmail(username);
            if (user == null) {
                user = this.findByPhone(username);
            }
        }
        return user;
    }

    @Override
    public Boolean checkPassword(Long userId, String password) {
        User user = getById(userId);
        if (user == null) {
            return Boolean.FALSE;
        }
        return new BCryptPasswordEncoder().matches(password, user.getPassword());
    }

    @Override
    public boolean save(User user) {
        //账号重复
        if (count(new QueryWrapper<User>().eq("username", user.getUsername())) > 0) {
            throw new RuntimeException("账号重复");
        }
        passwordService.encryptPassword(user);
        return super.save(user);
    }

    @Override
    public boolean updateById(User user) {
        if (count(new QueryWrapper<User>().ne("id", user.getId()).eq("username", user.getUsername())) > 0) {
            throw new RuntimeException("账号重复");
        }
        if (user.getId() != null) {
            UserUtils.update(user.getId());
        }
        return super.updateById(user);
    }
}
